package com.sky.zuor;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class LoginUtils {

    private static final String ENCRYPT_ALGORITHM = "AES/ECB/PKCS5Padding";

    public static void main(String[] args) throws Exception {
        String password = "abcd1234";
        long timestamp = System.currentTimeMillis();
        String secretKey = "C6RCkFFnxWFkT8kqd6+TeVWzSW5nrL6w28YRhpoiawg=";

        // 加密密码
        String encryptedPassword = encrypt(password, secretKey, timestamp);
        System.out.println("Encrypted Password: " + encryptedPassword);
        System.out.println(timestamp);

        // 解密密码
        String decryptedPassword = decrypt(encryptedPassword, secretKey, timestamp);
        System.out.println("Decrypted Password: " + decryptedPassword);
    }

    // 使用时间戳和密钥对密码进行加密
    public static String encrypt(String password, String secretKey, Long timestamp) throws Exception {
        SecretKeySpec keySpec = generateKey(secretKey);
        Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        String passwordBytes = password + timestamp.toString();
        byte[] encryptedBytes = cipher.doFinal(passwordBytes.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 使用时间戳和密钥对密码进行解密
    public static String decrypt(String encryptedPassword, String secretKey, Long timestamp) throws Exception {
        SecretKeySpec keySpec = generateKey(secretKey);
        Cipher cipher = Cipher.getInstance(ENCRYPT_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword));
        String s = new String(decryptedBytes, "UTF-8");
        return s.substring(0, s.length() - timestamp.toString().length());
    }

    // 生成密钥
    private static SecretKeySpec generateKey(String secretKey) throws NoSuchAlgorithmException {
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        byte[] keyBytes = sha.digest(secretKey.getBytes());
        // 仅取前 16 字节作为 AES 密钥
        byte[] aesKey = new byte[16];
        System.arraycopy(keyBytes, 0, aesKey, 0, aesKey.length);
        return new SecretKeySpec(aesKey, "AES");
    }
}